package 二叉树;

public class LC_235二叉搜索树最近公共祖先 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null)
            return null;
        //left
        if(root.val>p.val && root.val>q.val){
            TreeNode left=lowestCommonAncestor(root.left,p,q);
            if(left!=null)
                return left;
        }
        //right
        if(root.val<p.val && root.val<q.val){
            TreeNode right=lowestCommonAncestor(root.right,p,q);
            if(right!=null)
                return right;
        }
        return root;
    }
}
